﻿using System.Collections.Generic;
using System;
using UnityEngine;
public class RandomHelper
{
    static System.Random ran = new System.Random(GetRandomSeed());
    /// <summary>
    /// 算法：
    /// 1.每个元素权重+1命名为w，防止为0情况。
    /// 2.计算出总权重n。
    /// 3.每个元素权重w加上从0到(n-1)的一个随机数（即总权重以内的随机数），得到新的权重排序值s。
    /// 4.根据得到新的权重排序值s进行排序，取前面s最大几个。
    /// </summary>
    /// <param name="list">原始列表</param>
    /// <param name="count">随机抽取条数</param>
    /// <returns></returns>
    public static List<T> GetRandomList<T>(List<T> list, int count=1) where T : RandomObject
    {
        if (list == null || list.Count <= count || count <= 0)
        {
            return list;
        }
        
        //计算权重总和
        int totalWeights = 0;
        for (int i = 0; i < list.Count; i++)
        {
            totalWeights += list[i].weight + 1;  //权重+1，防止为0情况。
        }
        
        //随机赋值权重
        System.Random ran = new System.Random(GetRandomSeed());  //GetRandomSeed()防止快速频繁调用导致随机一样的问题 
        List<KeyValuePair<int, int>> wlist = new List<KeyValuePair<int, int>>();    //第一个int为list下标索引、第一个int为权重排序值
        for (int i = 0; i < list.Count; i++)
        {
            int w = (list[i].weight + 1) + ran.Next(0, totalWeights);   // （权重+1） + 从0到（总权重-1）的随机数
            wlist.Add(new KeyValuePair<int, int>(i, w));
        }
        
        //排序
        wlist.Sort(
          delegate (KeyValuePair<int, int> kvp1, KeyValuePair<int, int> kvp2)
          {
              return kvp2.Value - kvp1.Value;
          });       
        //根据实际情况取排在最前面的几个
        List<T> newList = new List<T>();
        for (int i = 0; i < count; i++)
        {
            T entiy = list[wlist[i].Key];
            newList.Add(entiy);
        }

        //随机法则
        return newList;
    }

    public static float RandomRate(int MaxValue=101,float Divisor = 1)
    {
        float value = ran.Next(1, MaxValue)/ Divisor;
        return value;
    }

    internal static float RandomNumber(int lower, int upper)
    {
        int value = ran.Next(lower, upper);
        return value;
    }

    

    /// <summary>
    /// 随机种子值
    /// </summary>
    /// <returns></returns>
    public static int GetRandomSeed()
    {

        byte[] bytes = new byte[4];
        System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
        rng.GetBytes(bytes);
        return BitConverter.ToInt32(bytes, 0);

    }
    /// <summary>
    /// 获取随机结果
    /// </summary>
    /// <param name="value"></param>
    /// <param name="totalValue"></param>
    /// <returns></returns>
    public static bool GetRandomResoult(int value,int totalValue=10000)
    {
        
        return ran.Next(0, totalValue) < value;
         
    }
   



}







/// <summary>
/// 权重对象
/// </summary>
public class RandomObject
{

    /// <summary>
    /// 权重
    /// </summary>
    public int weight { set; get; }

}